package com.es.action.compile;

import cn.hutool.core.util.StrUtil;
import com.es.common.Cache;
import com.es.util.file.FileUtil;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.File;
import java.util.List;

/**
 * 编译扩展，单例实现
 *
 * @author Will
 */
public class CompilerEx {

    private static volatile CompilerEx instance = null;

    private JavaCompiler javaCompiler;
    private String targetClassesPath;

    private CompilerEx() {
        this.javaCompiler = ToolProvider.getSystemJavaCompiler();
        this.targetClassesPath = (String) Cache.get("targetClassesPath");
    }

    /**
     * 单例实现
     *
     * @return instance
     */
    public static CompilerEx getInstance() {
        if (instance == null) {
            synchronized (CompilerEx.class) {
                if (instance == null) {
                    instance = new CompilerEx();
                }
            }
        }
        return instance;
    }

    /**
     * 编译 java文件
     *
     * @param javaPath java路径
     */
    public String compile(String javaPath) {

        if (!new File(javaPath).exists()) {
            System.err.println("编译文件不存在");
            return null;
        }

        String s = FileUtil.replaceName(targetClassesPath);
        File file = new File(s);
        if (!file.exists()) {
            file.mkdirs();
        }

        List<String> jars = FileUtil.getFileList(System.getProperty("user.dir"), "jar");
        String preLoadJarPath = (String) Cache.get("preLoadJarPath");
        if (StrUtil.isNotBlank(preLoadJarPath)) {
            String[] preLoadJarPathArr = preLoadJarPath.split(";");
            for (String prePath : preLoadJarPathArr) {
                List<String> jars2 = FileUtil.getFileList(prePath, "jar");
                jars.addAll(jars2);
            }
        }
        String s1 = convertList(jars);

        int status = javaCompiler.run(null, null, null,
                "-encoding", "UTF-8",
                "-cp", s1, "-d", s,
                FileUtil.replaceName(javaPath));
        if (status != 0) {
            System.err.println("编译失败");
            return null;
        }

        StringBuilder res = new StringBuilder();
        res.append("【").append(javaPath).append("】编译成功，").append("父路径【").append(s).append("】");

        System.out.println(res);
        return s + javaPath.replace(".java", ".class");
    }

    private String convertList(List<String> list) {
        StringBuilder sb = new StringBuilder();
        list.forEach(x -> sb.append(";").append(x));
        return sb.toString();
    }
}
